# coding=utf-8

import time
from django.db import models
from django.utils import timezone

from utils.exceptions import CustomError

from utils.wx.wechat import WeChat


class WechatTp(models.Model):
    component_appid = models.CharField(max_length=512, verbose_name=u'第三方平台appid')
    component_appsecret = models.CharField(max_length=512, verbose_name=u'第三方平台appsecret')
    m_encode_key = models.CharField(max_length=512, verbose_name=u'消息加密key')
    m_token = models.CharField(max_length=512, verbose_name=u'消息校验token')

    component_verify_ticket = models.CharField(max_length=512, verbose_name=u'验证票据', null=True)
    component_access_token = models.CharField(max_length=512, verbose_name=u'令牌', null=True)
    access_token_gtime = models.DateTimeField(verbose_name=u"获取令牌时间", null=True)
    expires_in = models.IntegerField(verbose_name=u'令牌有效期', null=True)

    class Meta:
        db_table = "wechat_tp"
        ordering = ['-id']
        index_together = ()
        verbose_name = u"第三方平台"
        default_permissions = ()

    @staticmethod
    def getDefault():
        tp = WechatTp.objects.filter().first()
        if not tp:
            raise CustomError(u'未找到微信第三方平台！')
        return tp

    @staticmethod
    def getByAppid(appid):
        component = WechatTp.objects.filter(component_appid=appid).first()
        if not component:
            raise CustomError(u'未找到相应的第三方平台！')
        return component

    def getAppid(self):
        return self.component_appid

    def getToken(self):
        return self.m_token

    def getEncodeKey(self):
        return self.m_encode_key

    def getAccessToken(self):
        if self.component_access_token:
            last_time = time.mktime(self.access_token_gtime.timetuple()) + self.expires_in
            now = time.mktime(timezone.now().timetuple())
            if last_time > now:
                return self.component_access_token
        res = WeChat.getComponentAccessToken(self.component_appid, self.component_appsecret, self.component_verify_ticket)
        self.refreshAccessToken(timezone.now(), res['component_access_token'], res['expires_in'])
        return self.component_access_token

    def getPreAuthCode(self):
        res = WeChat.getPreAuthCode(self.component_appid, self.getAccessToken())
        return res['pre_auth_code']

    def refreshVerifyTicket(self, component_verify_ticket):
        self.component_verify_ticket = component_verify_ticket
        self.save()

    def refreshAccessToken(self, gtime, component_access_token, expires_in):
        self.access_token_gtime = gtime
        self.component_access_token = component_access_token
        self.expires_in = expires_in
        self.save()

    def getAuthUrl(self, tenant_id):
        url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=' + self.getAppid() + '&pre_auth_code=' + self.getPreAuthCode()
        url += '&redirect_uri=https://xapp.aiche360.cn/api/redirect_authorize/' + tenant_id + '/&auth_type=2'
        return url

    def getTemplateList(self):
        template_list = WeChat.getCodeTemplateList(self.getAccessToken())
        return template_list
